package com.xjrsoft.module.customerTwo.AppManage.service_support_order.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.dto.ServiceSupportOrderTableListDto;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.entity.ServiceSupportOrder;
import com.xjrsoft.core.tool.utils.CollectionUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.entity.ServiceSupportOrderTable;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.service.IServiceSupportOrderTableService;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.dto.ServiceSupportOrderListDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.page.ConventPage;

import java.util.List;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.mapper.ServiceSupportOrderMapper;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.service.IServiceSupportOrderService;
import com.xjrsoft.core.mp.base.BaseService;
import com.xjrsoft.core.tool.utils.Func;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.stateMachine.ServiceSupportEvents;
import com.xjrsoft.module.customerTwo.AppManage.service_support_order.stateMachine.ServiceSupportStates;
import liquibase.pro.packaged.I;
import lombok.AllArgsConstructor;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 *  服务实现类
 *
 * @author lisen
 * @since 2024-04-23
 */
@Service
@AllArgsConstructor
public class ServiceSupportOrderServiceImpl extends BaseService<ServiceSupportOrderMapper, ServiceSupportOrder> implements IServiceSupportOrderService {

	@Resource
	IServiceSupportOrderTableService serviceSupportOrderTableService;
	@Resource
	private StateMachinePersister<ServiceSupportStates, ServiceSupportEvents, ServiceSupportOrder> persister;
	@Resource
	private StateMachine<ServiceSupportStates, ServiceSupportEvents> stateMachine;
	@Override
	public IPage<ServiceSupportOrder> getPageList(ServiceSupportOrderListDto pageListDto) {
		Wrapper<ServiceSupportOrder> wrapper = Wrappers.<ServiceSupportOrder>query().lambda()
				.like(!StringUtil.isEmpty(pageListDto.getOrder_number()), ServiceSupportOrder::getOrderNumber, pageListDto.getOrder_number())
				.ge(!StringUtil.isEmpty(pageListDto.getCreate_date_Start()), ServiceSupportOrder::getCreateDate, pageListDto.getCreate_date_Start())
				.le(!StringUtil.isEmpty(pageListDto.getCreate_date_End()), ServiceSupportOrder::getCreateDate, pageListDto.getCreate_date_End())
				.like(!StringUtil.isEmpty(pageListDto.getContract_number()), ServiceSupportOrder::getContractNumber, pageListDto.getContract_number())
				.like(!StringUtil.isEmpty(pageListDto.getContract_name()), ServiceSupportOrder::getContractName, pageListDto.getContract_name())
				.like(!StringUtil.isEmpty(pageListDto.getService_provider()), ServiceSupportOrder::getServiceProvider, pageListDto.getService_provider())
				.like(!StringUtil.isEmpty(pageListDto.getDescription()), ServiceSupportOrder::getDescription, pageListDto.getDescription())
				.like(!StringUtil.isEmpty(pageListDto.getContactor()), ServiceSupportOrder::getContactor, pageListDto.getContactor())
				.like(!StringUtil.isEmpty(pageListDto.getPhone()), ServiceSupportOrder::getPhone, pageListDto.getPhone())
				.like(!StringUtil.isEmpty(pageListDto.getState()), ServiceSupportOrder::getState, pageListDto.getState());
		return this.page(ConventPage.getPage(pageListDto), wrapper);
	}

	@Override
	public IPage<ServiceSupportOrderTable> getPageList(ServiceSupportOrderTableListDto pageListDto) {
		Wrapper<ServiceSupportOrderTable> wrapper = Wrappers.<ServiceSupportOrderTable>query().lambda()
				.like(!StringUtil.isEmpty(pageListDto.getProcess()),ServiceSupportOrderTable::getProcess, pageListDto.getProcess())
				.like(!StringUtil.isEmpty(pageListDto.getProcessor()),ServiceSupportOrderTable::getProcessor, pageListDto.getProcessor())
				.ge(!StringUtil.isEmpty(pageListDto.getCreate_date_Start()),ServiceSupportOrderTable::getCreateDate, pageListDto.getCreate_date_Start())
				.le(!StringUtil.isEmpty(pageListDto.getCreate_date_End()),ServiceSupportOrderTable::getCreateDate, pageListDto.getCreate_date_End());
		return serviceSupportOrderTableService.page(ConventPage.getPage(pageListDto), wrapper);
	}
	@Override
	public String addServiceSupportOrder(ServiceSupportOrder serviceSupportOrder) {
		serviceSupportOrder.setConfirmDate(LocalDateTime.now());
		serviceSupportOrder.setState("TODO");
		boolean isSuccess = this.save(serviceSupportOrder);
		return isSuccess ? serviceSupportOrder.getId().toString() : null;
	}

	//商户处理
	@Transactional
	@Override
	public String addServiceSupportOrderTable(ServiceSupportOrderTable serviceSupportOrderTable) {
		serviceSupportOrderTable.setCreateDate(LocalDateTime.now());
		ServiceSupportOrderTable orderTable = getByOrderId(serviceSupportOrderTable.getOrderId());
		if(orderTable!=null){
			orderTable.setIscurrent(0);
			serviceSupportOrderTableService.updateById(orderTable);
		}
		boolean isSuccess = serviceSupportOrderTableService.save(serviceSupportOrderTable);
		ServiceSupportOrder serviceSupportOrder = getById(serviceSupportOrderTable.getOrderId());
		if(serviceSupportOrder!=null){
			serviceSupportOrder.setState("DONE");
			updateById(serviceSupportOrder);
		}
		return isSuccess ? serviceSupportOrderTable.getId().toString() : null;
	}

	@Override
	public boolean confirm(Integer id,boolean bl){
		ServiceSupportOrder order = getById(id);
		if(bl){
			order.setState("CLOSED");
			return true;
		}else{
			order.setState("TODO");
			return false;
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateServiceSupportOrder(String id, ServiceSupportOrder serviceSupportOrder, List<ServiceSupportOrderTable> serviceSupportOrderTableList) {
		serviceSupportOrder.setId(Integer.valueOf(id));
		// ServiceSupportOrderTable
		List<String> serviceSupportOrderTableIdList = new ArrayList<>();
		for (ServiceSupportOrderTable serviceSupportOrderTable : serviceSupportOrderTableList) {
			String serviceSupportOrderTableId = String.valueOf(serviceSupportOrderTable.getId());
			if (StringUtil.isEmpty(serviceSupportOrderTableId)) {
				serviceSupportOrderTable.setOrderId(Integer.valueOf(id));
			} else {
				serviceSupportOrderTableIdList.add(serviceSupportOrderTableId);
			}
		}
		if (CollectionUtil.isNotEmpty(serviceSupportOrderTableIdList)) {
			serviceSupportOrderTableService.remove(Wrappers.<ServiceSupportOrderTable>query().lambda()
					.notIn(ServiceSupportOrderTable::getId, serviceSupportOrderTableIdList)
					.eq(ServiceSupportOrderTable::getOrderId, id));
		}
		serviceSupportOrderTableService.saveOrUpdateBatch(serviceSupportOrderTableList);
		serviceSupportOrder.setState(String.valueOf(ServiceSupportStates.DONE));
		return this.updateById(serviceSupportOrder);
	}

	@Override
	public boolean updateServiceSupportOrderTable(String id, ServiceSupportOrderTable serviceSupportOrderTable) {
		serviceSupportOrderTable.setId(Integer.valueOf(id));
		return serviceSupportOrderTableService.updateById(serviceSupportOrderTable);
	}
	@Override
	public boolean delete(String ids) {
		List<String> idList = Func.toStrList(ids);
		if (this.removeByIds(idList)) {
			serviceSupportOrderTableService.remove(Wrappers.<ServiceSupportOrderTable>query().lambda().in(ServiceSupportOrderTable::getOrderId, ids));
			return true;
		}
		return false;
	}

	@Override
	public boolean deleteTable(String ids) {
		List<String> idList = Func.toStrList(ids);
		if (serviceSupportOrderTableService.removeByIds(idList)) {
			return true;
		}
		return false;
	}
	@Override
	public List getServiceSupportOrderTableByParentId(String parentId){
		Wrapper wrapper = Wrappers.<ServiceSupportOrderTable>query().lambda().eq(ServiceSupportOrderTable::getOrderId, parentId).eq(ServiceSupportOrderTable::getIscurrent,1);
		return serviceSupportOrderTableService.list(wrapper);
	}

	private ServiceSupportOrderTable getByOrderId(Integer id){
		Wrapper wrapper =  Wrappers.<ServiceSupportOrderTable>query().lambda().eq(ServiceSupportOrderTable::getOrderId, id).eq(ServiceSupportOrderTable::getIscurrent,1);
		return serviceSupportOrderTableService.getOne(wrapper);
	}
	private synchronized boolean sendEvent(Message<ServiceSupportEvents> message, ServiceSupportOrder order) {
		boolean result = false;
		try {
			stateMachine.start();
			//尝试恢复状态机状态
			persister.restore(stateMachine, order);
			//添加延迟用于线程安全测试
			result = stateMachine.sendEvent(message);
			//持久化状态机状态
			persister.persist(stateMachine, order);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			stateMachine.stop();
		}
		return result;
	}

	@Override
	public ServiceSupportOrderTable getTableById(Integer id){
		return serviceSupportOrderTableService.getById(id);
	}
}